//
//  ZMJLrcView.m
//  Z-QQMusic
//
//  Created by zmj on 15/11/6.
//  Copyright © 2015年 zmj. All rights reserved.
//

#import "ZMJLrcView.h"
#import "ZMJLrcCell.h"
#import "ZMJLrc.h"
#import "ZMJMusicsTool.h"
#import "ZMJMusic.h"
#import "ZMJLrcTool.h"
#import "ZMJAudioTool.h"
#import <MediaPlayer/MediaPlayer.h>
@interface ZMJLrcView ()<UITableViewDataSource>
@property(nonatomic, weak) UITableView *lrcTableView;/**< 显示歌词的tableView */
@property(nonatomic, strong) NSArray *lrcs;/**< 存放歌词的数组 */
@property(nonatomic, assign) NSInteger currentIndex;/**< 与歌曲进度同步的歌词行号 */

@end

@implementation ZMJLrcView

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    if (self = [super initWithCoder:aDecoder]) {
        self.backgroundColor = [UIColor clearColor];
        self.showsHorizontalScrollIndicator = NO;
        self.pagingEnabled = YES;
        
    }
    return self;
}


//- (instancetype)initWithFrame:(CGRect)frame {
//    if (self = [super initWithFrame:frame]) {
//        self.backgroundColor = [UIColor clearColor];
//        self.showsHorizontalScrollIndicator = NO;
//        self.pagingEnabled = YES;
//        [self setupLrcTableView];
//    }
//    return self;
//}


- (void)awakeFromNib {
    [self setupLrcTableView];
}
- (void)layoutSubviews {
    [super layoutSubviews];
    if (self.contentSize.width == 0) {
        self.contentSize = CGSizeMake(self.bounds.size.width * 2, 0);
        // 设置tableView的frame
        [self setupLrcFrame];
    }
    
}

- (void)setupLrcTableView {
    // 添加歌词的tableView
    UITableView *lrcTableView = [[UITableView alloc] init];
    lrcTableView.backgroundColor = [UIColor clearColor];
    lrcTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    lrcTableView.dataSource = self;
    lrcTableView.rowHeight = 35;
    // 让tableView上下多出滚动区域
    lrcTableView.contentInset = UIEdgeInsetsMake(self.bounds.size.height * 0.5, 0, self.bounds.size.height * 0.5, 0);
    [self addSubview:lrcTableView];
    self.lrcTableView = lrcTableView;
}
- (void)setupLrcFrame {
    self.lrcTableView.frame = CGRectMake(self.bounds.size.width, 0, self.bounds.size.width, self.bounds.size.height);
}

/**
 *  
 [03:13.27]春天又来到了花开满山坡
 [03:17.52]种下希望就会收获
 [03:21.43]肥嘟嘟
 
 */
- (void)setCurrnetTime:(NSTimeInterval)currentTime {
    for (int i = 0; i < self.lrcs.count; i++) { // 遍历每句歌词
        // 取出当前句的歌词模型
        ZMJLrc *lrc = self.lrcs[i];
        // 取出下一句的歌词模型
        NSInteger nextIndex = i + 1;
        if (nextIndex >= self.lrcs.count )return;
        ZMJLrc *nextLrc = self.lrcs[nextIndex];
        
        // 一秒中遍历了n次,加入第一句符合,那么下面可能会调用多次,所以需要记录当前的行号
        if (currentTime >= lrc.time && currentTime < nextLrc.time && self.currentIndex != i) {
            
            NSIndexPath *previousIndexPath = [NSIndexPath indexPathForRow:self.currentIndex inSection:0];
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
            // 记录当前行号,再进行reload,否则,记录的是上一次的,则下面的不起作用(我草草哦啊哦草哦哦从哦草)
            self.currentIndex = i;
            // 刷新当前行
            [self.lrcTableView reloadRowsAtIndexPaths:@[previousIndexPath,indexPath] withRowAnimation:UITableViewRowAnimationNone];
            
            // 滚动到对应行
            [self.lrcTableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
            
            // 更新锁屏信息
            [self updateLockScreenInfo];

            
        }
        
        if (i == self.currentIndex) {
            CGFloat progress = (currentTime - lrc.time) / (nextLrc.time - lrc.time);
            // 拿到i行的cell
            ZMJLrcCell *lrcCell = [self.lrcTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
            // 设置cell.lrclabel的progress
            lrcCell.lrcLabel.progress = progress;
            
            // 设置控制器界面单句歌词label
            self.lrcLabel.text = lrc.lrcText;
            self.lrcLabel.progress = progress;
      
        }
        
        
    }
}

- (void)setLrcName:(NSString *)lrcName {
    _lrcName = lrcName;
    // 2.解析歌词
    self.lrcs = [ZMJLrcTool lrcArrayWithLrcName:lrcName];
    // 刷新数据
    [self.lrcTableView reloadData];
    // 当前播放行数清0
    self.currentIndex = 0;
}
/**
 *  更新锁屏信息
 */
- (void)updateLockScreenInfo {
    // 要得到绘制有3句歌词的歌手图片
    // 拿到3句歌词
    // 当前歌词
    NSString *currentLrcText = nil;
    ZMJLrc *currentLrc = self.lrcs[self.currentIndex];
    currentLrcText = currentLrc.lrcText;
    // 上一句歌词
    NSString *previousLrcText = nil;
    if (self.currentIndex - 1 >= 0){
        ZMJLrc *previousLrc = self.lrcs[self.currentIndex - 1];
        previousLrcText = previousLrc.lrcText;
    }
    // 下一句歌词
    NSString *nextLrcText = nil;
    if (self.currentIndex + 1 < self.lrcs.count) {
        ZMJLrc *nextLrc = self.lrcs[self.currentIndex + 1];
        nextLrcText = nextLrc.lrcText;
    }
    
    // 得到当前歌曲图片
    ZMJMusic *music = [ZMJMusicsTool playingMusic];
    UIImage *iconImage = [UIImage imageNamed:music.icon];
    
    // 开启上下文
    UIGraphicsBeginImageContext(self.bounds.size);
    // 绘制
    // 绘制图片
    [iconImage drawInRect:self.bounds];
    
    // 绘制3句歌词
    CGFloat iconImageHeight = iconImage.size.height;
    CGFloat iconImageWidth  = iconImage.size.width;
    // 前一句歌词frame
    CGRect preRect = CGRectMake(0, iconImageHeight - 75, iconImageWidth, iconImageHeight);
    // 绘制style,居中
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    style.alignment = NSTextAlignmentCenter;
    // 绘制一些富文本属性
    NSDictionary *preNextDict = @{
                                  NSFontAttributeName : [UIFont systemFontOfSize:14],
                                  NSParagraphStyleAttributeName : style,
                                  NSForegroundColorAttributeName : [UIColor grayColor]
                                  };
    // 前一句歌词绘制
    [previousLrcText drawInRect:preRect withAttributes:preNextDict];
    
    // 当前句歌词frame
    CGRect currRect = CGRectMake(0, iconImageHeight - 50, iconImageWidth, iconImageHeight);
    // 绘制一些富文本属性
    NSDictionary *currentDict = @{
                                  NSFontAttributeName : [UIFont systemFontOfSize:20],
                                  NSParagraphStyleAttributeName : style,
                                  NSForegroundColorAttributeName : [UIColor greenColor]
                                  };
    // 绘制当前句歌词
    [currentLrcText drawInRect:currRect withAttributes:currentDict];
    
    // 下一句歌词frame
    CGRect nextRect = CGRectMake(0, iconImageHeight - 25, iconImageWidth, iconImageHeight);
    // 绘制下一句歌词
    [nextLrcText drawInRect:nextRect withAttributes:preNextDict];
    
    // 得到水印图片
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    [self setLockScreenInfoWithMusic:music image:image];
    
    // 关闭上下文
    UIGraphicsEndImageContext();
}

/**
 *  设置锁屏信息
 *
 *  @param music 正在播放的歌曲
 *  @param image 设置锁屏界面画面
 */
- (void)setLockScreenInfoWithMusic:(ZMJMusic *)music image:(UIImage *)image{
    /*
    // MPMediaItemPropertyAlbumTitle
    // MPMediaItemPropertyAlbumTrackCount
    // MPMediaItemPropertyAlbumTrackNumber
    // MPMediaItemPropertyArtist
    // MPMediaItemPropertyArtwork
    // MPMediaItemPropertyComposer
    // MPMediaItemPropertyDiscCount
    // MPMediaItemPropertyDiscNumber
    // MPMediaItemPropertyGenre
    // MPMediaItemPropertyPersistentID
    // MPMediaItemPropertyPlaybackDuration
    // MPMediaItemPropertyTitle
     */
    // 获取锁屏中心
    MPNowPlayingInfoCenter *playingInfoCenter = [MPNowPlayingInfoCenter defaultCenter];
    // 设置锁屏信息
    NSMutableDictionary<NSString *, id> * info = [NSMutableDictionary dictionary];
    [info setObject:music.name forKey:MPMediaItemPropertyAlbumTitle]; // 歌曲名
    [info setObject:music.singer forKey:MPMediaItemPropertyArtist];// 歌手名
    [info setObject:@(self.duration) forKey:MPMediaItemPropertyPlaybackDuration]; // 时长
    MPMediaItemArtwork *artWork = [[MPMediaItemArtwork alloc] initWithImage:image];
    [info setObject:artWork forKey:MPMediaItemPropertyArtwork]; // 图片
    playingInfoCenter.nowPlayingInfo = info;
    
    // 让应用程序可以接受远程事件
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    
}


#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.lrcs.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    ZMJLrcCell *cell = [ZMJLrcCell lrcCellWithTableView:tableView];
    
    if (self.currentIndex == indexPath.row) {
        cell.lrcLabel.font = [UIFont systemFontOfSize:20];
    } else { // 还原 画制绿色的进度清0
        cell.lrcLabel.font = [UIFont systemFontOfSize:14.0];
        cell.lrcLabel.progress = 0;
    }
    cell.lrcLabel.text = ((ZMJLrc *)self.lrcs[indexPath.row]).lrcText;

    return cell;
}



@end
